<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.params" placeholder="角色名称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="getRoles">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="roles" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index">
            </el-table-column>
            <el-table-column prop="name" label="角色名称">
            </el-table-column>
            <el-table-column prop="description" label="备注">
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" :formatter="formatDate" sortable>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" :formatter="formatDate" sortable>
            </el-table-column>
            <el-table-column  label="操作" width="150">
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="20" :total="total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--编辑界面-->
        <el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false">
            <el-form :model="editForm" label-width="100px" :rules="editFormRules" ref="editForm">
                <el-row :gutter="30">
                    <el-col>
                        <el-form-item label="角色名称" prop="name">
                            <el-input v-model="editForm.name" :disabled="true" auto-complete="off"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="30">
                    <el-col>
                        <el-form-item label="描述" prop="description">
                            <el-input v-model="editForm.description" auto-complete="off"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="30">
                    <el-col>
                        <el-form-item label="是否为默认" prop="defaultRole">
                            <el-switch v-model="editForm.defaultRole"></el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="30">
                    <el-col>
                        <el-form-item label="菜单列表选项">
                            <el-tree ref="editTree"
                                     :data="permissions"
                                     show-checkbox
                                     node-key="id"
                                     :default-checked-keys="editForm.permissionIds"
                                     :props="defaultProps">
                            </el-tree>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="editFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
            </div>
        </el-dialog>

        <!--新增界面-->
        <el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
            <el-form :model="addForm" label-width="100px" :rules="addFormRules" ref="addForm">
                <el-row :gutter="30">
                    <el-col>
                        <el-form-item label="角色名称" prop="name">
                            <el-input v-model="addForm.name" auto-complete="off"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="30">
                    <el-col>
                        <el-form-item label="描述" prop="description">
                            <el-input v-model="addForm.description" auto-complete="off"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="30">
                    <el-col>
                        <el-form-item label="是否为默认" prop="defaultRole">
                            <el-switch v-model="addForm.defaultRole"></el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="30">
                    <el-col>
                        <el-form-item label="菜单列表选项">
                            <el-tree ref="addTree"
                                    :data="permissions"
                                    show-checkbox
                                    node-key="id"
                                    :props="defaultProps">
                            </el-tree>
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    import util from '../../common/js/util'
    import {addRole, batchRemoveRole, editRole, getAllPermission, getRoleListPage, removeRole,getChildrenByRoleId} from '../../api/api';

    export default {
        data() {
            let checkRoleName = (rule, value, callback) => {

                if (!value.startsWith("ROLE_")) {
                    return callback(new Error('请输入角色名称以ROLE_开头'));
                } else {
                    callback();
                }
            };
            return {
                filters: {
                    params:''
                },
                roles:[],
                permissions:[],
                total: 0,
                page: 1,
                listLoading: false,
                sels: [],//列表选中列
                editFormVisible: false,//编辑界面是否显示
                editLoading: false,
                editFormRules: {
                    name: [
                        { required: true, message: '请输入角色名称以ROLE_开头', trigger: 'blur' },
                        { min: 6, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' },
                        { validator: checkRoleName, trigger: 'blur' }
                    ],
                    description:[
                        { required: true, message: '请输入角色描述', trigger: 'blur' },
                    ]
                },
                //编辑界面数据
                editForm: {
                    id: 0,
                    name: '',
                    defaultRole: false,
                    description:'',
                    permissionIds:[]
                },
                //新增界面是否显示
                addFormVisible: false,
                addLoading: false,
                addFormRules: {
                    name: [
                        { required: true, message: '请输入角色名称以ROLE_开头', trigger: 'blur' },
                        { min: 6, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' },
                        { validator: checkRoleName, trigger: 'blur' }
                    ],
                    description:[
                        { required: true, message: '请输入角色描述', trigger: 'blur' },
                    ]
                },
                //新增界面数据
                addForm: {
                    id: 0,
                    name: '',
                    defaultRole: false,
                    description:'',
                    permissionIds:[]
                },
                defaultProps: {
                    children: 'children',
                    label: 'name'
                }
            }
        },
        methods: {
            formatDate: function(row, column, cellValue, index){
                if (cellValue == null)
                    return '';
                return util.formatDate.formatNum(cellValue,"yyyy-MM-dd");
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.editFormVisible = true;
                this.editForm = Object.assign({}, row);
                this.editForm.permissionIds = row.permissions.map(item=>item.permissionId);
                //获取当前编辑角色的子级权限
                let para = {roleId: row.id};
                getChildrenByRoleId(para).then(data=>{
                    if (data.code == 200){
                        this.$refs.editTree.setCheckedKeys(data.data,false);
                    }
                })

            },

            handleCurrentChange(val) {
                this.page = val;
                this.getRoles();
            },
            //显示新增界面
            handleAdd: function () {
                this.addFormVisible = true;
                this.addForm = {
                    id: 0,
                    name: '',
                    defaultRole: false,
                    description:'',
                    permissionIds:[]
                };
            },
            getRoles() {
                let para = {
                    page: this.page,
                    searchKey: this.filters.params
                };
                this.listLoading = true;
                getRoleListPage(para).then((data) => {
                    if (data.code == 200){
                        this.total = data.data.total;
                        this.roles = data.data.rows;
                        this.listLoading = false;
                    }
                    this.listLoading = false;
                });
                //加载权限信息
                getAllPermission().then(data=>{
                    if (data.code == 200){
                        this.permissions = data.data;
                    }
                });
            },
            //编辑
            editSubmit: function () {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editLoading = true;
                            let ck = this.$refs.editTree.getCheckedKeys();
                            let pk = this.$refs.editTree.getHalfCheckedKeys();
                            this.editForm.permissionIds = pk.concat(ck);
                            let para = Object.assign({}, this.editForm);
                            editRole(para).then((data) => {
                                if (data.code == 200){
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                } else {
                                    this.$message({
                                        message: '提交失败',
                                        type: 'error'
                                    });
                                }
                                this.$refs['editForm'].resetFields();
                                this.editFormVisible = false;
                                this.getRoles();
                                this.editLoading = false;
                            });
                        });
                    }
                });
            },
            //新增
            addSubmit: function () {
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.addLoading = true;
                            // 获取当前选中的权限
                            this.addForm.permissionIds = this.$refs.addTree.getCheckedKeys();
                            let para = Object.assign({}, this.addForm);
                            addRole(para).then((data) => {
                                this.addLoading = false;
                                if (data.code == 200){
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                } else {
                                    this.$message({
                                        message: '提交失败',
                                        type: 'error'
                                    });
                                }
                                this.$refs['addForm'].resetFields();
                                this.addFormVisible = false;
                                this.getRoles();
                                this.addLoading = false;
                            });
                        });
                    }
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                const ids = this.sels.map(item => item.id).toString();
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    let para = { ids: ids };
                    batchRemoveRole(para).then((data) => {
                        this.listLoading = false;
                        if (data.code == 200){
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                        } else {
                            this.$message({
                                message: data.msg,
                                type: 'error'
                            });
                        }
                        this.getRoles();
                        this.listLoading = false;
                    });
                }).catch(() => {

                });
            },
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    let para = { id: row.id };
                    removeRole(para).then((data) => {
                        this.listLoading = false;
                        if (data.code==200){
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                        } else {
                            this.$message({
                                message: data.msg,
                                type: 'error'
                            });
                        }
                        this.getRoles();
                        this.listLoading = false;
                    });
                }).catch(() => {

                });
            }
        },
        mounted() {
            this.getRoles();
        }
    }
</script>